#!/usr/bin/env node

const http = require('http');
const fs = require('fs');
const path = require('path');
const { Writable } = require('stream');

// 创建日志目录
const logsDir = path.join(__dirname, 'logs');
if (!fs.existsSync(logsDir)){
  fs.mkdirSync(logsDir);
}

// 获取当前日期并格式化为 YYYY-MM-DD
const currentDate = new Date().toISOString().slice(0, 10);
const logFilePath = path.join(logsDir, `${currentDate}.log`);

// 创建一个可写流来追加日志
const logStream = fs.createWriteStream(logFilePath, { flags: 'a' });

// 创建 HTTP 服务器
const server = http.createServer((req, res) => {
  // 获取当前时间并格式化为 YYYY/MM/DD hh:mm:ss
  const now = new Date().toISOString().replace(/T/, ' ').substring(0, 19);
  const logEntry = `${now}\t${req.method}\t${req.url}\t${req.httpVersion}\n`;
  const headersEntry = `${now}\t${JSON.stringify(req.headers)}\n`;

  // 写入日志
  logStream.write(logEntry);
  logStream.write(headersEntry);

  // 发送响应
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('hello\n');
});

// 服务器监听 8080 端口
server.listen(8080, () => {
  console.log('服务器运行在 http://localhost:8080/');
});
// cd logs
// ls
// cat 2024-9-22.log